package com.validateCodeYzm.zpf.lib;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author yeqin
 * @description
 * @date 17:19 2020/10/10
 */
public class LamUtil {

    @FunctionalInterface
    public interface MapperFunction<T, R>{
        R apply(T t) throws Exception;
    }

    public static <K,V,T> Map<K,V> arrayToMap(List<T> arr, Function<T,K> keyFn,Function<T,V> vfn){

        Map<K,V> map = new HashMap<>();

        for(T t:arr){
            map.put(keyFn.apply(t),vfn.apply(t));
        }

        return map;
    }


    public static <K,V,T> Result<Map<K,V>> arrayToMapOption(T[] arr, Function<T,K> keyFn,Function<T,V> vfn){
        List<T> collect = Arrays.stream(arr).collect(Collectors.toList());
        return arrayToMapOption(collect,keyFn,vfn);
    }

    public static <K,V,T> Result<Map<K,V>> arrayToMapOption(List<T> list, Function<T,K> keyFn,Function<T,V> vfn){
        try{
            return Result.of(arrayToMap(list,keyFn,vfn));
        }catch(Exception e){
            e.printStackTrace();
            return Result.error(e);
        }
    }
}
